import { Injectable } from '@angular/core';
import {
    CanActivate, Router,
    ActivatedRouteSnapshot,
    RouterStateSnapshot,
    CanActivateChild,
    CanLoad, UrlTree
} from '@angular/router';
import { LoginInOutService } from '@core/services/common/login-in-out.service';
import { AuthService } from '@core/services/common/auth.service';
import { UserService } from '@services/common/user.service';
import { NzMessageService } from 'ng-zorro-antd/message';



@Injectable({
    providedIn: 'root',
})
export class AuthRouterGuard implements CanActivate, CanActivateChild {
    codeArray!: string[];
    constructor(
        private loginInOutService: LoginInOutService,
        private router: Router,
        private authService: AuthService,
        private userService: UserService,
        private message: NzMessageService
    ) { }

    canActivate(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): boolean {
        //console.logR('canActivate', route, state);
        const url: string = state.url;
        return this.checkAuthAccessResource(route);
    }

    canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        //console.logR('canActivateChild', route, state);
        return this.canActivate(route, state);
    }

    checkAuthAccessResource(route: ActivatedRouteSnapshot,): boolean {
        if (!!route.data.code) {
            //this.codeArray = ['router.login.loginButton', 'router.login'];
            this.codeArray = this.authService.getAuthorizedAccessResource();
            const bool: boolean = this.authorizedAccessResource(route.data.code);
            console.log('checkAuth',bool);
            if (!bool) {
                this.message.error('您没有权限访问该模块');
                //this.router.navigate(['login']);
                return false;
            }
        }
        return true;
    }

    authorizedAccessResource(authCode: string | undefined) {
        if (!authCode) {
            return true;
        }
        return this.codeArray.includes(authCode) ? true : false;
    }
}
